﻿using log4net.Repository.Hierarchy;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChatServerLib
{
    /// <summary>
    /// 加入聊天
    /// </summary>
    public class JOIN : CommandBase<ChatSession, StringRequestInfo>
    {

        public override void ExecuteCommand(ChatSession session, StringRequestInfo requestInfo)
        {
            string username = requestInfo.Body;

            // 用户未输入昵称
            if (string.IsNullOrWhiteSpace(username))
            {
                session.Send("Enter Nickname: \r\n Use: JOIN YourNickName");
                return;
            }

            var sessions = session.AppServer.GetSessions(_ => !string.IsNullOrWhiteSpace(_.UserName)).ToList();

            // 昵称已经存在
            if (sessions.Any(_ => _.UserName.Equals(username, StringComparison.OrdinalIgnoreCase)))
            {
                session.Send("Nickname [" + username + "] exists, please get another one.");
                return;
            }

            // 昵称不存在，可以加入聊天
            session.UserName = username;
            session.Send(string.Format("Yoo.. [{0}], welcome. You can chat now.\r\n Current Online User:  {1}", username, string.Join(" , ", sessions.Select(_=>_.UserName).ToArray())));
        }
    }
}
